package com.zifeng.study.springbootredis.service;

import com.zifeng.study.springbootredis.common.SecKillProductStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author 吴梓锋
 * @version 1.0.0
 * @date 2022/05/24 14:40:38
 * @description
 */
@Service
@Slf4j
public class RedisSecKillService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource(name = "secKillScript")
    DefaultRedisScript<String> secKillScript;

    /**
     * 初始化库存
     *
     * @param productKey   商品key
     * @param productCount 库存数
     */
    public void initProductCount(String productKey, String productCount) {
        stringRedisTemplate.delete(productKey);
        stringRedisTemplate.opsForValue().set(productKey, productCount);
    }

    public String secKill(String productKey, String userId) {
        // 存储秒杀成功用户的队列
        String secSuccessSetName = productKey + ":user:set";
        // 执行lua脚本
        String result = stringRedisTemplate.execute(secKillScript, Arrays.asList(productKey, secSuccessSetName), userId);

        if (Objects.equals(result, SecKillProductStatus.SEC_KILL_EMPTY)) {
            return "商品已抢完！";
        } else if (Objects.equals(result, SecKillProductStatus.SEC_KILL_REPEAT)) {
            return "您已抢购成功，请勿重复抢购！";
        } else if (Objects.equals(result, SecKillProductStatus.SEC_KILL_SUCCESS)) {
            return "抢购成功！";
        }

        return "抢购失败!";
    }

}
